import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import router from '@/router'
import { getToken, removeToken } from '@/utils/auth'

// create an axios instance
const service = axios.create({
  // 要向http://ihrm-java.itheima.net中请求数据不符合同源策略,产生跨域,所以使用代理服务器,因为服务器与服务器之间没有跨域且能保证同源 http://localhost:9528/+api+request url
  // 在vue.config.js中devSever中配置proxy(代理服务器),用target去访问后台的服务器
  // baseURL: 'http://ihrm-java.itheima.net',
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    // console.log(store.getters)
    // console.log(config, 333)
    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation

      config.headers['Authorization'] = 'Bearer ' + getToken()
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    // console.log(response.data)
    const res = response.data
    // 做响应成功的判断
    // console.log(res.success === true)
    if (res.success === true) {
      return res
    } else {
      Message({
        message: res.message || 'Error',
        type: 'error',
        duration: 5 * 1000
      })
      return Promise.reject(new Error('请求错误!'))
    }

    //   if (res.code === 50008 || res.code === 50012 || res.code === 50014) {

    //     MessageBox.confirm('You have been logged out, you can cancel to stay on this page, or log in again', 'Confirm logout', {
    //       confirmButtonText: 'Re-Login',
    //       cancelButtonText: 'Cancel',
    //       type: 'warning'
    //     }).then(() => {
    //       store.dispatch('user/resetToken').then(() => {
    //         location.reload()
    //       })
    //     })
    //   }
    //   return Promise.reject(new Error(res.message || 'Error'))
    // } else {
    //   return res
    // }
  },
  error => {
    // 当token失效时返回到登录页面,响应的状态码10002时清除cookie里的token和vuex里的token并且跳转到登录页面
    if (error.response.data.code === 10002) {
      removeToken()
      store.commit('user/SET_TOKEN', '')
      router.push('login')
    }
    return Promise.reject(error)
  }
)

export default service
